/** @type {const('rollup').RollupOptions} */
const commonjs = require("@rollup/plugin-commonjs");
const nodeResolve = require("@rollup/plugin-node-resolve");
const typescript = require("@rollup/plugin-typescript");
const babel = require("@rollup/plugin-babel");
const terser = require("@rollup/plugin-terser");
const alias = require("@rollup/plugin-alias");
const json = require("@rollup/plugin-json");
const replace = require("@rollup/plugin-replace");
const server = require("rollup-plugin-serve");
const nodePolyfills = require("rollup-plugin-node-polyfills");
const name = "InvestMap";

const isDev = process.env.NODE_ENV === "dev";
const format = process.env.FORMAT;

const plugins = [
  nodeResolve({
    preferBuiltins: false,
    browser: true,
  }),
  commonjs({
    include: [
      "node_modules/**",
      "src/libs/fengmap.map-nologo-v3.0.9.min.js",
      "src/libs/fengmap.analyser.min.js",
    ], // 包括node_modules下的所有文件
  }),
  typescript(),
  babel({
    exclude: [
      "node_modules/**",
      "src/libs/fengmap.map-nologo-v3.0.9.min.js",
      "src/libs/fengmap.analyser.min.js",
    ],
    extensions: [".ts", ".tsx", "js"],
    babelHelpers: "runtime",
  }),
  !isDev && terser(),
  alias({
    entries: {
      "@": "./src",
      "#": "./types",
    },
  }),
  json(),
  replace({
    preventAssignment: true,
    "process.env.NODE_ENV": JSON.stringify(`${process.env.NODE_ENV}`), // 否则会报：process is not defined的错
  }),
  format === "iife" && server({ open: true, contentBase: "" }),
  nodePolyfills(),
];

const iife = {
  input: "src/main.ts",
  output: {
    file: "dist/investMap.min.js",
    format: "iife",
    name,
    sourcemap: isDev,
    globals: {
      fs: "null",
    },
    content: "window",
  },
  plugins: plugins,
  external: ["fs"],
};

const esm = {
  input: "src/main.ts",
  output: {
    file: "dist/investMap.esm.js",
    format: "es",
    sourcemap: isDev,
  },
  globals: {
    axios: "axios",
  },
  plugins: plugins,
  external: ["axios"],
};

const cjs = {
  input: "src/main.ts",
  output: {
    file: "dist/investMap.cjs.js",
    format: "cjs",
    sourcemap: isDev,
    name,
  },
  globals: {
    axios: "axios",
  },
  plugins: plugins,
  external: ["axios"],
};
let config = [];

if (format === "all" || !isDev) {
  config = [iife, esm, cjs];
} else if (format === "iife") {
  config = [iife];
} else if (format === "esm") {
  config = [esm];
} else if (format === "cjs") {
  config = [cjs];
}
module.exports = config;
